package com.mfcxy.interceptor;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mfcxy.entity.User;
import com.mfcxy.exception.CustomException;


/**
 * 权限检查
 * @author mfcxy
 *
 */
public class AdminRbacInterceptor2 extends HandlerInterceptorAdapter{
private static Logger log = Logger.getLogger(AdminRbacInterceptor2.class);

@Autowired
private HttpSession session;
	
	/**
	 * 渲染视图之后被调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
	
	/**
	 * 调用目标方法之后，但渲染视图之前被调用
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * 该方法在目标方法之前被调用
	 * 若返回值为true，则继续调用后续操作
	 * 若返回值为false，则不会调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		log.info("---------------------------------------------");
		//log.info(request.getRequestURL());
		//log.info(request.getContextPath());
		log.info(arg2);
		
		String path = request.getServletPath();
		log.info(path);
		
		
		
		//从session中获取当前用户的权限
		List<Map<String , Object>> plist = (List<Map<String, Object>>) session.getAttribute("permissions");
		log.info(plist);
		
		log.info(plist.contains(path));
		
		log.info("---------------------------------------------");
		log.info("该方法在目标方法之前被调用:权限");
		
		
		User user = (User) session.getAttribute("user");
		if(user.getId() == 1) {
			return true;
		}
		
		if(plist.contains(path)) {
			return true;
		} else {
			throw new CustomException("你没有权限");
		}
		
	}
	
}
